import argparse
import json
import os
from pathlib import Path

from log_manager import LogManager


def format_digit(digit, length):
    """格式化数字，补零"""
    return str(digit).zfill(length)


def get_srt_time_text(time, is_milli=False):
    """
    获取SRT格式的时间文本
    Args:
        time: 时间（微秒或毫秒）
        is_milli: 是否是毫秒单位
    """
    if is_milli:
        time = time // 1000  # 转换为微秒

    # 转换为毫秒
    millisecond = time % 1000
    time = time // 1000

    # 转换为时分秒
    second = time % 60
    time = time // 60
    minute = time % 60
    hour = time // 60

    return (
        f"{format_digit(hour, 2)}:{format_digit(minute, 2)}:"
        f"{format_digit(second, 2)},{format_digit(millisecond, 3)}"
    )


def format_srt(index, content, start_time, end_time):
    """格式化为SRT格式"""
    if isinstance(content, str):
        text = json.loads(content).get("text", "")
    else:
        text = content.get("text", "")
    return f"{index}\n{start_time} --> {end_time}\n{text}\n\n"


def format_txt(content):
    """格式化为TXT格式"""
    if isinstance(content, str):
        text = json.loads(content).get("text", "")
    else:
        text = content.get("text", "")
    return f"{text}\n\n"


def convert_track_to_subtitle(track, texts, is_milli, output_format="srt"):
    """将一条轨道转换为字幕文本"""
    segments = track.get("segments", [])
    subtitle_text = ""
    index = 0

    for segment in segments:
        content = texts.get(segment.get("material_id"))
        if not content:
            continue

        time_range = segment.get("target_timerange", {})
        start_time = time_range.get("start", 0)
        duration = time_range.get("duration", 0)
        end_time = start_time + duration

        start_time_text = get_srt_time_text(start_time, is_milli)
        end_time_text = get_srt_time_text(end_time, is_milli)

        index += 1
        if output_format == "srt":
            subtitle_text += format_srt(index, content, start_time_text, end_time_text)
        else:
            subtitle_text += format_txt(content)

    return subtitle_text


def convert_json_to_subtitle(json_data, output_format="srt"):
    """
    转换剪映JSON为字幕文件
    Args:
        json_data: 剪映JSON数据
        output_format: 输出格式（srt或txt）
    """
    # 获取平台信息
    is_milli = json_data.get("platform", {}).get("os") != ""

    # 提取文本材料
    texts = {}
    for text in json_data.get("materials", {}).get("texts", []):
        texts[text.get("id")] = text.get("content")

    # 处理每个轨道
    subtitle_files = {}
    for track in json_data.get("tracks", []):
        if track.get("type") != "text":
            continue
        subtitle_text = convert_track_to_subtitle(track, texts, is_milli, output_format)
        if subtitle_text:
            subtitle_files[track.get("id")] = subtitle_text

    return subtitle_files


def expoet_srt(output_dir, format="srt"):
    project_path = select_project()
    if not project_path:
        LogManager.log("未选择项目")
        return
    # 读取JSON文件，指定编码为utf-8
    with open(project_path / "draft_info.json", "r", encoding="utf-8") as f:
        json_data = json.load(f)

    # 转换字幕
    subtitle_files = convert_json_to_subtitle(json_data, format)

    # 确定输出目录
    output_dir = os.path.expanduser(output_dir)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 保存文件
    result = []
    for track_id, content in subtitle_files.items():
        output_file = os.path.join(
            output_dir, f"{project_path.name}_{track_id}.{format}"
        )
        with open(output_file, "w", encoding="utf-8") as f:
            f.write(content)
        LogManager.log(f"已生成字幕文件: {output_file}")
        result.append(output_file)
    return result


def select_project():
    """选择剪映项目"""
    path = os.path.expanduser("~/Movies/CapCut/User Data/Projects/com.lveditor.draft")
    path = Path(path)
    files = []
    for p in path.iterdir():
        file = p / "draft_info.json"
        if file.exists() and file.is_file():
            item = {
                "name": p.name,
                "path": p,
                "time": file.stat().st_mtime,
            }
            files.append(item)
    files.sort(key=lambda x: x["time"])
    for index, file in enumerate(files):
        LogManager.log(f"[{index + 1}]{file['name']}")
    LogManager.log("请输入项目序号:")
    while True:
        index = int(input())
        if index > 0 and index <= len(files):
            file = files[index - 1]
            return file["path"]
        else:
            LogManager.log("输入错误")


def main():
    parser = argparse.ArgumentParser(description="剪映字幕文件转换工具")
    parser.add_argument("output_dir", help="输出目录")
    parser.add_argument(
        "--format",
        "-f",
        choices=["srt", "txt"],
        default="srt",
        help="输出格式（srt或txt）",
    )
    args = parser.parse_args()
    return expoet_srt(args.output_dir, args.format)


if __name__ == "__main__":
    main()
